<template>
  <div class="shopcart_contain">
    <div class="list_shopcart">
      <el-table
              ref="multipleTable"
              :data="shopcartList"
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="handleSelectionChange">
        <el-table-column
                type="selection"
                width="55"
                label="全选">
        </el-table-column>
        <el-table-column
                label="商品名称"
                width="500">
          <template slot-scope="scope">
            <el-col :span="8"><img :src="scope.row.product.productLogoImg"></el-col>
            <el-col :span="16"><div class="price_name_item">
              <span class="">{{scope.row.product.productName}}</span>
              <span>{{scope.row.productColor.productColor}}</span>
            </div></el-col>
          </template>
        </el-table-column>
        <el-table-column
                label="单价"
                width="120">
          <template slot-scope="scope">
            <span>{{scope.row.product.productPrice}}元</span>
          </template>
        </el-table-column>
        <el-table-column
                label="数量"
                width="150">
          <template slot-scope="scope">
            <el-col :span="24">
              <div class="button_group">
                <button @click="decrement(scope.$index,scope.row)">-</button><span>{{scope.row.shopcart.productNum}}</span><button @click="increment(scope.$index, scope.row)">+</button>
              </div>
            </el-col>

<!--            <el-input-number v-model="selectedProductList[scope.$index].shopcart.productNum"  :min="1" :max="scope.row.product.productCount" label="数量" size="mini" @change="btnChange(scope.$index, scope.row)"></el-input-number>-->
          </template>
        </el-table-column>
        <el-table-column
                label="小计"
                width="100"
                show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.shopcart.productNum*scope.row.product.productPrice}}元
          </template>
        </el-table-column>
        <el-table-column
                label="操作"
                width="100">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete" circle @click="buttonClick(scope.$index, scope.row)"></el-button>
          </template>
        </el-table-column>

      </el-table>

    </div>
    <div class="bottom_commit">
      <div class="data_item"></div>
          <div>
            <span>共{{shopcartList.length}} 件商品，已选择 {{multipleSelection.length}}件</span>
            <span>合计：{{totalPrice}}元</span>
            <el-button type="warning" @click="commitClick">去结算</el-button>
          </div>
    </div>
    <bottom-bar></bottom-bar>
  </div>

</template>

<script>
  import {request} from "network/request";
  import BottomBar from "../bottomBar/BottomBar";
  export default {
    name: "ListShopcart",
    components:{
      BottomBar
    },
    created() {
      request({
        url: '/shopcart/selectListByUser',
        params:{
          userId: this.$store.state.userId
        },
      }).then(res => {
        this.shopcartList = res.data.data;
        this.selectedProductList = this.shopcartList;
        console.log(this.$store.state.username);
        console.log(res);
      });
    },

    data(){
      return{
        multipleSelection: [],
        shopcartList: [],
        selectedProcutCount: 0,
        totalPrice: 0,
        isClick: [],
        account: 0,
      }

      },
    methods:{
      handleSelectionChange(val) {
        console.log(val);
        //每当勾选了的时候， 就要遍历勾选的商品， 进行遍历，得到商品的数量
        this.multipleSelection = val;
        if(this.multipleSelection.length === 0){
          this.selectedProcutCount = 0;
          this.isClick = [];
          this.totalPrice = 0;  //总价格为0
        }else{
          this.selectedProcutCount = 0;
          this.totalPrice = 0;
          for(let item in this.multipleSelection){
            //设置总个数
            this.selectedProcutCount += this.multipleSelection[item].shopcart.productNum;
            //设置totalPrice
            this.totalPrice += this.multipleSelection[item].shopcart.productNum * this.multipleSelection[item].product.productPrice;
          }
        }
        console.log(this.multipleSelection);
        console.log(this.selectedProcutCount);
      },

      //删除购物车记录
      buttonClick(index, row){
        this.$confirm('确定删除吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //先动态删除shopcartList里面的数据
          this.shopcartList.splice(index, 1);
          //再发送请求，发送到后端， 删除该购物车记录
          request({
            url: '/shopcart/delete/' + row.user.userId + '/' + row.shopcart.productId,
            method: 'delete',

          }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      //减少数组选中的数量
      decrement(index, row){
        if(row.shopcart.productNum > 1){
          row.shopcart.productNum--;
          if(this.multipleSelection.length > 0){
            this.isClick[index] = true;
            let count = 0;
            for(let i in this.isClick){
              if(this.isClick[i] === true){
                count += 1;
              }
            }
            if(count <= this.multipleSelection.length){
              this.selectedProcutCount--;
              this.totalPrice -= this.shopcartList[index].product.productPrice;
            }

          }
        }


      },
      //增加数组选中的数量
      increment(index, row){
        row.shopcart.productNum++;
        if(this.multipleSelection.length > 0) {
          this.isClick[index] = true;
          let count = 0;
          for(let i in this.isClick){
            if(this.isClick[i] === true){
              count += 1;
            }
          }
          if(count <= this.multipleSelection.length){
            this.selectedProcutCount++;
            this.totalPrice += this.shopcartList[index].product.productPrice;
          }

        }
      },

      //下单操作
      commitClick(){
        if(this.shopcartList.length != 0){
          //如果账户余额不足， 则要提示用户先进行充值
          let that = this;
          if(this.account === 0){
            this.account = this.shopcartList[0].user.account;
          }

          let userId = this.shopcartList[0].user.userId;
          if( this.account < this.totalPrice){
            this.$confirm('账户余额：' + this.account + ' 元，若想下单，请进行充值', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$prompt('请输入充值数目', '我的账户', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^[0-9]*$/,
                inputErrorMessage: '请输入数字'
              }).then(({ value }) => {
                let account = parseFloat(value);
                //发送请求， 请求账户充值~
                request({
                  url: '/user/recharge',
                  method: 'put',
                  data:{
                    userId,
                    account,
                  }
                }).then(res => {
                  this.account = res.data.data;
                });
                this.$message({
                  type: 'success',
                  message: '你的账户余额是: ' + (parseFloat(value) + this.account) + '元',
                });

              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '取消充值'
                });
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '未进行账户充值，下单失败'
              });
            });
          }else{
            //如果账户余额够的话，  发送网络请求， 下单操作， 然后扣除账户余额
            //封装productOrder对象,
            let productOrder = {
              productId: '',
              productColorId: '',
              productNum: 0,
              userId: '',
              adressId: '',
              orderStatus: 1,
            };
            let list = [];
            // 循环选中的 商品购物车列表，发送网络请求
            for(let index in this.multipleSelection){
              productOrder.productId = this.multipleSelection[index].shopcart.productId;
              productOrder.productColorId = this.multipleSelection[index].productColor.productColorId;
              console.log(productOrder.productColorId);
              productOrder.productNum = this.multipleSelection[index].shopcart.productNum;
              productOrder.userId = this.multipleSelection[index].user.userId;
              productOrder.adressId = this.multipleSelection[index].adress.adressId;
              productOrder.orderStatus = 2;
              list[index] = productOrder;
              console.log(list);
            }
            request({
              url: 'product-order/insert',
              method: 'post',
              data: list,
            }).then(res => {
              this.account = res.data.data;
              this.$alert('下单成功', '用户操作', {
                confirmButtonText: '确定',
              });
            });

          }
        }
      },
    },



  }
</script>

<style scoped>
  img{
    width: 80%;
  }

  .price_name_item{
    margin-top: 10%
  }
  .shopcart_contain{
    width: 100%;
  }
  .list_shopcart{
      width: 80%;
    margin: 0 auto;
  }
  .button_group{
    border: 1px solid #E0E0E0;
    height: 30px;
    line-height: 30px;
  }
  .button_group button{
    background-color: white;
    border: none;
    width: 24%;
    height: 100%;

  }
  .button_group button :hover{
    border: none;
    background-color: #B0B0B0 !important;
  }
  .button_group span{
    width: 52%;
    display: inline-block;
    text-align: center;
  }
  .button_group button :active{
    border: 1px solid white;
    background-color: #B0B0B0;
  }

  .bottom_commit{
    margin-top: 30px;
    width: 100%;
    height: 40px;
    font-size: 12px;
    text-align: center;
  }
  .bottom_commit span{
    padding: 0 20px;
  }
</style>
